package com.example.ycq.service.impl;

import com.example.ycq.dao.MyBatisUserDao;
import com.example.ycq.pojo.User;
import com.example.ycq.service.MyBatisUserService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MybatisUserServiceImpl implements MyBatisUserService, ApplicationContextAware {

    @Autowired
    private MyBatisUserDao myBatisUserDao=null;

    private ApplicationContext applicationContext=null;

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,timeout = 1)//isolation:隔离
    public User getUser(Long id) {
        return myBatisUserDao.getUser(id);
    }




    @Override
    //REQUIRED_NEW:无论当前是否有事务，都会创建新事务运行方法，与当前事务相互独立
    @Transactional(isolation=Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW)
    //NESTED:发生异常时，此方法事务回滚，主方法事务不回滚。NESTED：嵌套的
    //@Transactional(isolation=Isolation.READ_COMMITTED,propagation = Propagation.NESTED)
    public int insertUser(User user) {
        return myBatisUserDao.insertUser(user);
    }

    @Override
    //propagation:传播
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int insertUsers(List<User> userList) {
        int count=0;
        //从IOC容器中取出代理对象
        MyBatisUserService myBatisUserService=applicationContext.getBean(MyBatisUserService.class);
        for(User user:userList){
            count+=myBatisUserService.insertUser(user);
        }
        return count;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }
}
